import { Controller } from "egg";

const userList: any = [];

class MessageController extends Controller {
  public async index() {
    const ctx: any = this.ctx;
    console.log(ctx);
    //const app=this.app;
    // await ctx.app.redis.get("sub").subscribe();
    // const message = ctx.args[0];
    // await ctx.socket.emit("res", "i has accept your message: " + message);
  }

  /**
   * 处理登录
   */
  public async login() {
    const ctx: any = this.ctx;
    //const app=this.app;
    //await ctx.app.redis.get("sub").subscribe();
    const data = ctx.args[0];
    //console.log(ctx.socket);
    ctx.socket.nickname = data.nickname;
    const item = {
      socket: ctx.socket,
      nickname: data.nickname
    };
    userList.push(item);
    //ctx.socket.join('001');
    //await ctx.app.io.of('/').to('001').emit('res', { msg: 'welcome', id: ctx.socket.id });
    //await ctx.socket.emit("res", "i has accept your message: " + message);
  }

  /**
   * 处理注册
   */
  public async register() {
    const ctx: any = this.ctx;
    //const app=this.app;
    //await ctx.app.redis.get("sub").subscribe();
     const data = ctx.args[0];
    console.log(data);
    for(let i=0;i<userList.length;i++){
      if(userList[i].nickname===data.to){
        userList[i].socket.emit('res',data.msg);
      }
    }

    //await ctx.app.io.of('/').to('001').emit('res', { msg: 'welcome', id: ctx.socket.id });
    //await ctx.socket.emit("res", "i has accept your message: " + message);
  }
}

export default MessageController;
